const importLazy = require('import-lazy')(require);
const inquirer = require('inquirer');

const Okapi = importLazy('../okapi/okapiRepository.js');
const ModuleService = importLazy('../okapi/moduleService.js');

module.exports = async function assignTenant(pakeage) {
  const answers = await inquirer.prompt([
    {
      type: 'input',
      name: 'okapiUrl',
      message: '请输入okapiUrl地址',
    },
    {
      type: 'input',
      name: 'tenant',
      message: '请输入租客类型',
    },
  ]);
  const { okapiUrl, tenant } = answers;

  const okapi = new Okapi(okapiUrl, tenant);
  const moduleService = new ModuleService(okapi);
  const moduleId = `${pakeage.name.replace(/^@/, '').replace('/', '_')}-${pakeage.version}`;

  return moduleService
    .enableModuleForTenant(moduleId, tenant)
    .then(() => {
      console.log(`Tenant ${tenant} assigned permission success!!!`);
    })
    .catch((err) => {
      console.log('Error assigning in.', err);
    });
};
